<?php
class CategoriesController extends AppController {
	public $name = 'Categories';
	public $components = array('Session', 'Security', 'Auth');

	public function index(){
		$this->set('categories', $this->Category->find('all'));
	}

	public function add(){
		if($this->request->is("post")){
			$this->Category->create();
			if($this->Category->Save($this->request->data)){
				$this->Session->setFlash("Category created", "default", array("class" => "success"));
				$this->redirect(array("action" => "index"));
			}
		}
	}

	public function edit($id = null){
		$this->Category->id = $id;
		if(!$this->Category->exists()){
			throw new NotFoundException("Category not found");
		}

		if($this->request->is("get")){
			$this->request->data = $this->Category->read();
		}else{
			if($this->Category->save($this->request->data)){
				$this->Session->setFlash("Category updated", "default", array("class" => "success"));
				$this->redirect(array("action" => "index"));
			}
		}
	}

	public function delete(){
		if($this->request->is("get")){
			throw new MethodNotAllowedException();
		}elseif($this->request->is("post")){
			$i = 0;
			$this->loadModel('GroupCategory');
			foreach($this->request->data['Category']['selectedCategories'] AS $categoryId){
				$this->GroupCategory->deleteAll(array('category_id' => $categoryId));
				$this->Category->id = $categoryId;
				$this->Category->delete();
				$i++;
			}
			$this->Session->setFlash($i . ": Categories have been deleted.", "default", array('class' => 'error-message'));
			$this->redirect(array("action" => "index"));
		}
	}

}